#include <QDebug>
#include "json-serializator.h"
#include "serializable.h"

using namespace Core;

JSONSerializator::JSONSerializator()
{
}

void JSONSerializator::beginObject()
{
    data << "{";
}

void JSONSerializator::endObject()
{
    if (data.last().at(data.last().length() - 1) == ',')
        data.last().remove(-1, 1);

    data << "}";
}

void JSONSerializator::writeProperty(const QString &propertyName, const QVariant &propertyValue)
{
    if (propertyName != "objectName")
    {
        if (propertyValue.type() == QVariant::String)
            data << QString("%1: \"%2\",").arg(propertyName).arg(propertyValue.toString());
        else
            data << QString("%1: %2,").arg(propertyName).arg(propertyValue.toString());
    }
}

void JSONSerializator::beginList(const QString &propertyName)
{
    data << QString("%1: [").arg(propertyName);
}

void JSONSerializator::writeListItem(const QVariant &item)
{
    if (item.type() == QVariant::String)
        data << QString("\"%1\",").arg(item.toString());
    else
    if (item.type() == QVariant::UserType)
        data << QString("%1,").arg(item.value<ObjectString>());
    else
        data << QString("%1,").arg(item.toString());
}

void JSONSerializator::endList()
{
    if (data.last().at(data.last().length() - 1) == ',')
        data.last().remove(-1, 1);

    data << "],";
}

void JSONSerializator::clear()
{
    data.clear();
}

ObjectString JSONSerializator::result()
{
    return data.join("\n");
}
